const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const cors = require('cors');

const app = express();

// 配置CORS允许跨域
app.use(cors({
  origin: true,
  methods: ["GET", "POST"],
  credentials: true
}));

const server = http.createServer(app);

// 配置Socket.IO
const io = new Server(server, {
  cors: {
    origin: true,
    methods: ["GET", "POST"],
    credentials: true
  }
});

let clientCount = 0;
const connectedClients = new Map();

// 向指定客户端推送消息
function pushMessageToClient(clientId, message) {
  if (connectedClients.has(clientId)) {
    connectedClients.get(clientId).emit('message', {
      text: message,
      timestamp: new Date(),
      type: 'server-push'
    });
    console.log(`已向客户端 ${clientId} 推送消息: ${message}`);
  }
}

// 向所有客户端推送消息
function pushMessageToAllClients(message) {
  io.emit('message', {
    text: message,
    timestamp: new Date(),
    type: 'server-broadcast'
  });
  console.log(`已向所有客户端推送消息: ${message}`);
}

// 定时推送系统消息
setInterval(() => {
  const systemMessage = `系统通知：当前在线 ${clientCount} 人 | 服务器时间 ${new Date().toLocaleTimeString()}`;
  pushMessageToAllClients(systemMessage);
}, 5000);

// 处理Socket连接
io.on('connection', (socket) => {
  console.log('新客户端连接:', socket.id);
  clientCount++;
  connectedClients.set(socket.id, socket);
  
  // 发送欢迎消息
  socket.emit('message', {
    text: '欢迎连接到服务器！',
    timestamp: new Date(),
    type: 'server-push'
  });
  
  // 更新在线人数
  io.emit('clientCount', clientCount);
  
  // 监听客户端消息并打印
  socket.on('message', (data) => {
    console.log(222,data)
    console.log(`收到客户端 ${socket.id} 的消息:`, {
      内容: data.text,
      时间: new Date(data.timestamp).toLocaleString()
    });
    
    // 回应客户端
    socket.emit('message', {
      text: `服务器已收到: "${data.text}"`,
      timestamp: new Date(),
      type: 'server-push'
    });
  });
  
  // 处理断开连接
  socket.on('disconnect', () => {
    console.log('客户端断开连接:', socket.id);
    clientCount--;
    connectedClients.delete(socket.id);
    io.emit('clientCount', clientCount);
  });
});

// 手动推送消息的API
app.get('/push', (req, res) => {
  const { clientId, message } = req.query;
  if (!message) return res.status(400).send('请提供消息内容');
  
  if (clientId) {
    pushMessageToClient(clientId, message);
    res.send(`已向客户端 ${clientId} 推送消息`);
  } else {
    pushMessageToAllClients(message);
    res.send('已向所有客户端推送消息');
  }
});

const PORT = 3001;
server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log(`手动推送消息: http://localhost:${PORT}/push?message=你的消息`);
});